package org.example.user.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import org.example.common.config.Result;
import org.example.common.utils.RedisKit;
import org.example.user.dto.LoginDTO;
import org.example.user.service.ISysUserService;
import org.example.user.service.RedisService;
import org.example.user.vo.LoginVO;
import org.example.user.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/auth")
public class SysLoginController {

    @Autowired
    private ISysUserService sysUserService;

    private RedisKit redisKit;

    @Autowired
    public void setRedisKit(RedisKit redisKit) {
        this.redisKit = redisKit;
    }

    //用户登录
    @PostMapping("/login")
    public Result loign(@RequestBody @Valid LoginDTO loginDTO) {
        LoginVO login = sysUserService.login(loginDTO);
        return Result.ok(login);
    }

    //用户登出
    @PostMapping("/logout")
    public Result logout() {
        sysUserService.logout();
        return Result.ok();
    }

    //获取用户信息
    @GetMapping("/info")
    public Result userInfo() {
        UserInfoVO userAuthInfo = sysUserService.getUserAuthInfo();
        return Result.ok(userAuthInfo);
    }

    //刷新访问令牌
    @PostMapping("/refreshToken")
    public Result refreshToken(@RequestParam @NotEmpty(message = "刷新令牌不能为空") String refreshToken) {
        String accessToken = sysUserService.refreshToken(refreshToken);

        return Result.ok(accessToken);
    }

    //修改登录密码
    @PutMapping("/changePassword")
    public Result changeLoginPassword(
            @RequestParam("oldPassword")  @NotBlank(message = "原密码不能为空")  String oldPassword,
            @RequestParam("newPassword")  @Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d).+$", message = "密码必须包含字母和数字") String newPassword
    ){
        return Result.ok(sysUserService.changeLoginPassword(oldPassword, newPassword));
    }

    //短信验证码登录
    @PostMapping("/smsLogin")
    public Result smsLogin(
            @RequestParam @Pattern(regexp = "^1[3-9]\\d{9}$") String mobile,
            @RequestParam String smsCode
    ){
        return Result.ok(sysUserService.smsLogin(mobile, smsCode));
    }
}
